package com.atguigu.daijia.payment.service.impl;

import com.atguigu.daijia.common.constant.MqConst;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.service.RabbitService;
import com.atguigu.daijia.driver.client.DriverAccountFeignClient;
import com.atguigu.daijia.model.entity.payment.PaymentInfo;
import com.atguigu.daijia.model.enums.TradeType;
import com.atguigu.daijia.model.form.driver.TransferForm;
import com.atguigu.daijia.model.form.payment.PaymentInfoForm;
import com.atguigu.daijia.model.vo.order.OrderRewardVo;
import com.atguigu.daijia.model.vo.payment.WxPrepayVo;
import com.atguigu.daijia.order.client.OrderInfoFeignClient;
import com.atguigu.daijia.payment.mapper.PaymentInfoMapper;
import com.atguigu.daijia.payment.service.WxPayService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import static java.lang.System.currentTimeMillis;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public WxPrepayVo createWxPayment(PaymentInfoForm paymentInfoForm) {
        try {
            // 添加支付记录到支付记录表
            // 如果存在订单支付记录，则不需要进行添加
            LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PaymentInfo::getOrderNo, paymentInfoForm.getOrderNo());
            PaymentInfo paymentInfo = paymentInfoMapper.selectOne(lambdaQueryWrapper);
            if (ObjectUtils.isEmpty(paymentInfo)){
                paymentInfo = new PaymentInfo();
                BeanUtils.copyProperties(paymentInfoForm, paymentInfo);
                paymentInfo.setPaymentStatus(1);
                paymentInfoMapper.insert(paymentInfo);
            }

            // 交换机发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_ORDER,
                    MqConst.QUEUE_PAY_SUCCESS,
                    paymentInfoForm.getOrderNo());
            System.out.println("发送消息成功");
            //2 创建微信支付使用对象
//        JsapiServiceExtension service =
//                new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();

            //3 创建request对象，封装微信支付需要参数
//        PrepayRequest request = new PrepayRequest();
//        Amount amount = new Amount();
//        amount.setTotal(paymentInfoForm.getAmount().multiply(new BigDecimal(100)).intValue());
//        request.setAmount(amount);
//        request.setAppid(wxPayV3Properties.getAppid());
//        request.setMchid(wxPayV3Properties.getMerchantId());
            //string[1,127]
//        String description = paymentInfo.getContent();
//        if(description.length() > 127) {
//            description = description.substring(0, 127);
//        }
//        request.setDescription(description);
//        request.setNotifyUrl(wxPayV3Properties.getNotifyUrl());
//        request.setOutTradeNo(paymentInfo.getOrderNo());

            //获取用户信息
//        Payer payer = new Payer();
//        payer.setOpenid(paymentInfoForm.getCustomerOpenId());
//        request.setPayer(payer);

            //是否指定分账，不指定不能分账
//        SettleInfo settleInfo = new SettleInfo();
//        settleInfo.setProfitSharing(true);
//        request.setSettleInfo(settleInfo);

            //4 调用微信支付使用对象里面方法实现微信支付调用
//        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);

            //5 根据返回结果，封装到WxPrepayVo里面
            WxPrepayVo wxPrepayVo = new WxPrepayVo();
            wxPrepayVo.setTimeStamp(String.valueOf(currentTimeMillis()));
            return wxPrepayVo;
        }catch (Exception e){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public Boolean queryPayStatus(String orderNo) {
        LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(lambdaQueryWrapper);
        Integer paymentStatus = paymentInfo.getPaymentStatus();
        return paymentStatus.equals(1);
    }

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;

    @Autowired
    private DriverAccountFeignClient driverAccountFeignClient;

    /**
     * 支付成功后的回调
     * @param orderNo
     */
    @Override
    @GlobalTransactional
    public void handleOrder(String orderNo) {
        // 修改订单状态
        orderInfoFeignClient.updateOrderPayStatus(orderNo);
        // 获取系统奖励，打入司机账户
        OrderRewardVo orderRewardVo = orderInfoFeignClient.getOrderRewardFee(orderNo).getData();
        if (orderRewardVo != null && orderRewardVo.getRewardFee().doubleValue() > 0){
            TransferForm transferForm = new TransferForm();
            transferForm.setTradeNo(orderNo);
            transferForm.setTradeType(TradeType.REWARD.getType());
            transferForm.setContent(TradeType.REWARD.getContent());
            transferForm.setAmount(orderRewardVo.getRewardFee());
            transferForm.setDriverId(orderRewardVo.getDriverId());
            driverAccountFeignClient.transfer(transferForm);
        }
    }

    //微信支付成功后，进行的回调
//    @Override
//    public void wxnotify(HttpServletRequest request) {
//        //1.回调通知的验签与解密
//        //从request头信息获取参数
//        //HTTP 头 Wechatpay-Signature
//        // HTTP 头 Wechatpay-Nonce
//        //HTTP 头 Wechatpay-Timestamp
//        //HTTP 头 Wechatpay-Serial
//        //HTTP 头 Wechatpay-Signature-Type
//        //HTTP 请求体 body。切记使用原始报文，不要用 JSON 对象序列化后的字符串，避免验签的 body 和原文不一致。
//        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
//        String nonce = request.getHeader("Wechatpay-Nonce");
//        String timestamp = request.getHeader("Wechatpay-Timestamp");
//        String signature = request.getHeader("Wechatpay-Signature");
//        String requestBody = RequestUtils.readData(request);
//
//        //2.构造 RequestParam
//        RequestParam requestParam = new RequestParam.Builder()
//                .serialNumber(wechatPaySerial)
//                .nonce(nonce)
//                .signature(signature)
//                .timestamp(timestamp)
//                .body(requestBody)
//                .build();
//
//        //3.初始化 NotificationParser
//        NotificationParser parser = new NotificationParser(rsaAutoCertificateConfig);
//        //4.以支付通知回调为例，验签、解密并转换成 Transaction
//        Transaction transaction = parser.parse(requestParam, Transaction.class);
//
//        if(null != transaction && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
//            //5.处理支付业务
//            this.handlePayment(transaction);
//        }
//    }
}
